package com.night.card.controller;

import cn.hutool.core.date.DateUtil;
import com.github.pagehelper.PageInfo;
import com.night.card.service.interfs.CardService;
import com.night.card.vo.CardDataVo;
import com.night.common.entity.ResultVo;
import com.night.common.entity.card.Card;
import com.night.common.entity.card.CardIn;
import com.night.common.entity.card.group.AddGroup;
import com.night.common.entity.student.Student;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

/**
 * @ClassName: CardController
 * @Description: 校园卡控制类
 * @author: CHX42
 * @date: 2022/10/24-10:43
 * @version: v1.0
 */
@RestController
@Slf4j
@RequestMapping("/api/card/")
public class CardController {
    @Resource
    private CardService cardService;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @PostMapping("/add")
    public ResultVo<?> add(@RequestBody @Validated({AddGroup.class}) Card card) {
        cardService.add(card);
        return ResultVo.SUCCESS;
    }

    @PostMapping("/list")
    public ResultVo<?> getList(@RequestBody CardDataVo<Card, Card> cardDataVo) {
        List<Card> cardList = Arrays.asList(cardDataVo.getData());
        cardDataVo.getPageInfo().setList(cardList);
        PageInfo<Card> cardPageInfo = cardService.getBy(cardDataVo.getPageInfo());
        return new ResultVo<>(cardPageInfo);
    }

    @PostMapping("/getById")
    public ResultVo<?> getBy(@RequestBody Card card) {
        Card reCard = cardService.getById(card.getId());
        return new ResultVo<>(reCard);
    }


    @PostMapping("/update")
    public ResultVo<?> update(@RequestBody Card card) {
        cardService.update(card);
        return ResultVo.SUCCESS;
    }

    @PostMapping("/getByStudentId")
    public ResultVo<?> getByStudentId(@RequestBody Student student) {
        return new ResultVo<>(cardService.getByStudentId(student.getId()));
    }


    @PostMapping("/inMoney")
    public ResultVo<?> inMoney(@Validated({com.night.common.entity.card.group.AddGroup.class}) @RequestBody CardIn cardIn) {
        cardIn.setInTime(DateUtil.now());
        MessagePostProcessor messagePostProcessor = message -> {
            message.getMessageProperties().setExpiration(60 * 1000 + "");//设置消息过期时间
            return message;
        };
        rabbitTemplate.convertAndSend("inMoneyExchange","innMoney",cardIn,messagePostProcessor);
        return ResultVo.SUCCESS;
    }


}
